package Queue;

import stack.LinearNode;

/**
 * Created by Administrator on 2017/10/15/015.
 */
public class LinkedQueue<T> implements Queue<T> {
    private int count;
    private LinearNode<T> front, rear;

    public LinkedQueue() {
        count = 0;
        front = rear = null;
    }
    public void enqueue(T element) {
        LinearNode<T> node = new LinearNode<T>(element);
        if (count==0)
            front = node;
        else
            rear.setNext(node);

        rear = node;
        count++;
    }
    public T dequeue() throws Exception {
        if (count==0)
            throw new Exception("队列是空的！");
        T result = front.getElement();
        front = front.getNext();
        count--;
        if (isEmpty())
            rear = null;
        return result;
    }
    public T first() throws Exception {
        if (count==0)
            throw new Exception("队列是空的！");
        return front.getElement();
    }

    public boolean isEmpty() {
        return (count == 0);
    }
    public int size() {
        return count;
    }
    public String toString() {
        String result = "<top of Queue>\n";
        LinearNode current = front;
        while (current != null)
        {
            result = result + (current.getElement()).toString() + "\n";
            current = current.getNext();
        }
        return result + "<bottom of Queue>";
    }
}
